package com.restaurant.web.android.utill;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.util.ArrayList;
import java.util.Date;

import com.restaurant.domain.Menuorder;
import com.restaurant.domain.Tableorder;

public class PrintToKitchen implements Printable{

	private ArrayList<Menuorder> listmMenuorders = null;
	private Tableorder tableorder = null;
	
	public PrintToKitchen(ArrayList<Menuorder> listmMenuorders, Tableorder tableorder){
		this.listmMenuorders = listmMenuorders;
		this.tableorder = tableorder;
	}
	
	@Override
	public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
		
		if (pageIndex > 0) {
            return NO_SUCH_PAGE;
		}
		
		Graphics2D g2d = (Graphics2D)g;
		g2d.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 8));
		FontMetrics fontMetrics = g2d.getFontMetrics(g2d.getFont());
	    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
		
	    int x = 10;
	    int y = 20;
	    String text = "Order No: " + tableorder.getTableorderID();
	    g2d.drawString(text, getXMidPoing(fontMetrics, pageFormat, text), y);
	    y+=15;
	    text = tableorder.getTables().getTablediscription();
	    g2d.drawString(text, getXMidPoing(fontMetrics, pageFormat, text), y);
	    y+=15;
	    drawLine(g2d, y);
	    y+=15;
	    text = new Date().toString();
	    g2d.drawString(text, x, y);
	    y+=15;
	    drawLine(g2d, y);
	    y+=15;
	    g2d.drawString("Menu", x+20, y);
	    g2d.drawString("Qty", getXPointRightAlign(fontMetrics, pageFormat, "Qty"), y);
	    y+=15;
	    drawLine(g2d, y);
	    y+=15;
	    for(int i=0;i<listmMenuorders.size();i++){
	    	g2d.drawString(listmMenuorders.get(i).getMenu().getMenuname(), x+5, y);
	    	g2d.drawString("1", getXPointRightAlign(fontMetrics, pageFormat, "1"), y);
	    	y+=15;
	    }
	    drawLine(g2d, y);
	    return PAGE_EXISTS;
	}
	
	private void drawLine(Graphics2D g2d, int y){
		for(int i=0;i<225;i+=6){
			g2d.drawString("-", i, y);
		}
	}
	
	private int getXPointRightAlign(FontMetrics fm, PageFormat pf, String text){
        return (int)(3*72) - fm.stringWidth(text) - 20;
    }
   
    private int getXMidPoing(FontMetrics fm, PageFormat pf, String text){
        return (int)(3*72)/2 - fm.stringWidth(text)/2;
    }

}
